package com.yuqing.sentimentapp.statistics;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.linkface.baselibrary.http.BaseApiService;
import com.linkface.baselibrary.utils.FileUtils;
import com.linkface.baselibrary.utils.LogUtil;
import com.yuqing.sentimentapp.BuildConfig;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseFragment;
import com.yuqing.sentimentapp.base.BaseObserver;
import com.yuqing.sentimentapp.home.bean.NewsDetailDataBean;
import com.yuqing.sentimentapp.interfaces.DownloadListener;
import com.yuqing.sentimentapp.module.DownloadPdfHelp;
import com.yuqing.sentimentapp.module.ModuleManager;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.net.NetWorkUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cookie;

/**
 * A simple {@link Fragment} subclass.
 */
public class StatisticsFragment extends BaseFragment {
    private final static String PDFJS_PREFIX = "file:///android_asset/pdfjs/web/viewer.html?file=";
    @BindView(R.id.webView)
    WebView mWebView;
    private String webUrl = "";
    private boolean isUrl;
    private String title;
    private boolean isPDF;
    private DownloadPdfHelp downloadPdfHelp;

    public static StatisticsFragment start(String url, boolean isUrl, boolean isPDF) {
        StatisticsFragment fragment = new StatisticsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("webUrl", url);
        bundle.putBoolean("isUrl", isUrl);
        bundle.putBoolean("isPDF", isPDF);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_statistics;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initIntentData();
        initWebView();
        if (isUrl) {
            if (isPDF) {
                loadPdf();
            } else {
                mWebView.loadUrl(webUrl);
            }
        } else {
            //此时webUrl是newsId
//            loadData();
        }
    }

    @Override
    protected void initPresenter() {

    }


    private void loadPdf() {
        if (downloadPdfHelp == null) {
            downloadPdfHelp = new DownloadPdfHelp(getActivity());
        }
        downloadPdfHelp.downloadFile(BuildConfig.Base_URL + "/analysisView?id=" + webUrl, webUrl + ".pdf", new DownloadListener() {

            @Override
            public void onStart() {
                startProgressDialog();
            }

            @Override
            public void onProgress(int currentLength) {
//                        LogUtil.d("当前进度：" + currentLength);
            }

            @Override
            public void onFinish(String localPath) {
                getActivity().runOnUiThread(() -> {
                    Log.d("DownloadPdfHelp", "file path =  " + localPath);
                    loadLocalPDF(localPath);
                    stopProgressDialog();
                });
            }

            @Override
            public void onFailure(String erroInfo) {

            }
        });
    }

    public void loadLocalPDF(String path) {
        mWebView.loadUrl(PDFJS_PREFIX + "file://" + path);
    }

    public void loadOnlinePDF(String url) {
        mWebView.loadUrl(PDFJS_PREFIX + url);
    }

    private void loadData() {
        ModuleManager.getInstance().getNewsDetailResult(getActivity(), SharePrefrenceHelper.getLoginMobile(), webUrl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NewsDetailDataBean>() {
                    @Override
                    protected void hideDialog() {
                        stopProgressDialog();
                    }

                    @Override
                    protected void showDialog() {
                        startProgressDialog();
                    }

                    @Override
                    protected void onSuccess(NewsDetailDataBean newsDataBean) {
                        if (newsDataBean == null) {
                            return;
                        }
                        NewsDetailDataBean.DataBean data = newsDataBean.getData();
                        if (data == null) {
                            return;
                        }
//                        mTvTitle.setText(data.getTitle());
                        mWebView.loadDataWithBaseURL(null, data.getContent(), "text/html", "utf-8", null);
                    }

                    @Override
                    protected void onFailure(String message) {

                    }
                });
    }

    private void initIntentData() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            webUrl = arguments.getString("webUrl");
            title = arguments.getString("title");
            isUrl = arguments.getBoolean("isUrl", false);
            isPDF = arguments.getBoolean("isPDF", false);
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int scale = dm.densityDpi;
        if (scale == 240) { //设置自动适配
            mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (scale == 160) {
            mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else {
            mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        }
//        支持特殊的javascript脚本语句
        mWebView.setWebChromeClient(new WebChromeClient());
        //取消滚动条
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        //触摸焦点起作用
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);

        //支持javascript脚本语句
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        mWebView.getSettings().setDatabaseEnabled(true);
        //开启 Application Caches 功能
        mWebView.getSettings().setAppCacheEnabled(true);

        //webview屏幕适配
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        //支持自动加载图片
        mWebView.getSettings().setLoadsImagesAutomatically(true);

        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        //支持缩放
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setDisplayZoomControls(false);//不显示缩放按钮
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setSavePassword(true);
        mWebView.setWebViewClient(new WebViewClient() {
            //页面加载开始
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            //页面加载完成
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (TextUtils.isEmpty(url)) {
                    return false;
                }
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                // 不要使用super，否则有些手机访问不了，因为包含了一条 handler.cancel()
                // super.onReceivedSslError(view, handler, error);
                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                sslErrorHandler.proceed();
            }
        });
        //5.0以上需要开启第三方Cookie存储
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
        }
        // 特别注意：5.1以上默认禁止了https和http混用，以下方式是开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        CookieSyncManager.createInstance(getActivity());
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 将cookie同步到WebView
     *
     * @param url    WebView要加载的url
     * @param cookie 要同步的cookie
     * @return true 同步cookie成功，false同步cookie失败
     * @Author JPH
     */
    public static boolean syncCookie(Context context, String url, String cookie) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(context);
        }
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie(url, cookie);//如果没有特殊需求，这里只需要将session id以"key=value"形式作为cookie即可
        String newCookie = cookieManager.getCookie(url);
        return TextUtils.isEmpty(newCookie) ? false : true;
    }

    @Override
    public void onResume() {
        if (mWebView != null) {
            mWebView.onResume();//恢复
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        if (mWebView != null) {
            mWebView.onPause(); //暂停应用内所有WebView //mWebView.onResume(); 恢复。
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        FileUtils.deleteSDDir(DownloadPdfHelp.PATH_CHALLENGE_PDF);
        if (mWebView != null) {
            mWebView.destroy();
        }
        super.onDestroy();
    }
}
